# encoding=utf-8

# ---------------------------------------------------------------------------------------------------------
#
#  引用文档处理
#
# ---------------------------------------------------------------------------------------------------------

from core.markdown import Markdown
import re
import logging
import config

# 文档名称字号拆分符
CONST_DOCUMENT_SN_SPLIT = '#'


# 匹配全名(书名号)
REFERENCE_PATTERN_A = re.compile(r'《[^《》]+[^\(.+\)]》')
# 匹配字号(全角括号)
REFERENCE_PATTERN_B = re.compile(r'（[^（）]+[^\(.+\)]）')
# 匹配字号(半角括号)
REFERENCE_PATTERN_C = re.compile(r'\([^\(\)]+[^\(\/.+\)]\)')


class Reference(object):
    '''引用文档
    '''

    def __init__(self) -> None:
        super().__init__()

        self.id = ''
        # 字号，原始名称的第一节
        self.sn_name = ''
        # 去掉字号的后一段
        self.name = ''

        # 原始名称
        self.origin_name = ''
        self.is_reference = False

    def link_prefix(self):
        '''通过判断是否手册文档，决定是否返回链接前缀
        '''
        return config.REFERENCE_LINK_PREFIX if self.is_reference else ''


class Handler(object):
    '''处理文档引用
    '''

    def __init__(self) -> None:
        super().__init__()
        self.reference_documents = []
        self.handbook_documents = []
        self.changed_handbook_documents = []

        self._handbook_markdown_path = config.HANDBOOK_PATH + 'markdown/'
        self._reference_markdown_path = config.REFERENCE_PATH + 'markdown/'

        # 所有文档对象（包括引用文档、手册文档）
        self._references = []
        self._reference_map = {}

    def _prepare(self):
        '''预处理
        '''
        # 数据准备
        logging.info('准备引用文档信息')

        # 引用文档
        for d in self.reference_documents:
            cells = d.name.split(CONST_DOCUMENT_SN_SPLIT)

            r = Reference()
            r.id = d.id
            r.origin_name = d.name
            r.is_reference = True

            # 检测是否有字号
            if len(cells) > 1:
                # 字号
                r.sn_name = cells[0]
                # 名称
                r.name = cells[1]
            else:
                # 名称
                r.name = cells[0]

            self._references.append(r)

        # 手册文档
        for d in self.handbook_documents:
            r = Reference()
            r.id = d.id
            r.name = d.name
            r.origin_name = d.name
            r.is_reference = False

            self._references.append(r)

        # 转换映射(name-Reference)或者(sn_name-Reference)
        for r in self._references:
            if r.sn_name:
                self._reference_map[r.sn_name] = r
            else:
                self._reference_map[r.name] = r

            pass

        pass

    def _do_handle(self, md):
        '''处理单个markdown文档
        '''

        if config.AUTO_DOCUMENT_LINK:
            logging.info('处理文档引用 [%s] [%s]', md.document_id, md.full_name)
        else:
            return

        temp_contents = ''
        count = 0

        # 打开 markdown ，替换匹配到的文档名
        with open(md.full_path(), mode='r', encoding='utf-8') as r:
            while True:
                line = r.readline()
                if not line or line is None:
                    break

                # 通过正则，匹配全名(书名号)
                for n in REFERENCE_PATTERN_A.findall(line):
                    name = n[1:-1]
                    logging.debug('1---------- %s', n)

                    ref = self._reference_map.get(name)
                    if ref:
                        count += 1
                        logging.info('1-链接到引用 《%s》', name)
                        # line = line.replace(n, '《[{}](/{}{}/)》'.format(name, ref.link_prefix(), ref.id))
                        line = line.replace(n, '《<a href="#/{}{}/">{}</a>》'.format(ref.link_prefix(), ref.id, name))

                # 通过正则，匹配文号(全角括号)
                for n in REFERENCE_PATTERN_B.findall(line):
                    name = n[1:-1]
                    logging.debug('2---------- %s', n)

                    ref = self._reference_map.get(name)
                    if ref:
                        count += 1
                        logging.info('2-链接到引用 （%s）', name)
                        # line = line.replace(n, '（[{}](/{}{}/)）'.format(name, ref.link_prefix(), ref.id))
                        line = line.replace(n, '（<a href="#/{}{}/">{}</a>）'.format(ref.link_prefix(), ref.id, name))

                # 通过正则，匹配文号(半角括号)
                for n in REFERENCE_PATTERN_C.findall(line):
                    name = n[1:-1]
                    logging.debug('3---------- %s', n)

                    ref = self._reference_map.get(name)
                    if ref:
                        count += 1
                        logging.info('3-链接到引用 (%s)', name)
                        # line = line.replace(n, '([{}](/{}{}/))'.format(name, ref.link_prefix(), ref.id))
                        line = line.replace(n, '(<a href="#/{}{}/">{}</a>)'.format(ref.link_prefix(), ref.id, name))

                temp_contents += line

        with open(md.full_path(), mode='w', encoding='utf-8') as w:
            w.writelines(temp_contents)

        if count > 0:
            logging.info('[%s]-----> 共链接引用%s个', md.name, count)

    def handle(self):
        '''处理文档引用
        '''

        print('-------------------------------------------------------------------------------------------------------')

        # 遍历所有变更的手册文档
        if config.AUTO_DOCUMENT_LINK:
            logging.info('检测到已开启“AUTO_DOCUMENT_LINK”，自动处理文档引用(%d)', len(self.changed_handbook_documents))
        else:
            logging.info('检测到未开启“AUTO_DOCUMENT_LINK”，忽略文档引用处理')

        self._prepare()

        for d in self.changed_handbook_documents:

            md = Markdown()
            md.name = d.name
            md.full_name = d.name + '.md'
            md.document_id = d.id
            md.markdown_path = self._handbook_markdown_path

            self._do_handle(md)

        logging.info('处理引用文档完成(%s)', len(self.changed_handbook_documents))
